﻿Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Data.Linq
Imports System.Text
Imports DevComponents
Imports System.Data
Imports System.Text.RegularExpressions
Imports TNCDAL
Imports HTLibrary
Public Class ucTongXangDau

    Dim moil As New MOilPrice
    Dim util As New Utilities
    Dim munitprice As New MOilUnitPrices
    Dim col1 As DataGridViewTextBoxColumn
    Dim col2 As DataGridViewComboBoxColumn
    Dim col3 As DevComponents.DotNetBar.Controls.DataGridViewDateTimeInputColumn
    Dim TotRowCount As Integer
    Private NewTruckID As Integer
    Private isNewOilExpense As Boolean
    Private isEditOilExpese As Boolean
    Dim blnLocthang As Boolean = False
    Dim blnLocquy As Boolean = False
    Dim blnLocnam As Boolean = False
    Dim filterTab1 As Boolean = False
    Dim blnLocthang2 As Boolean = False
    Dim blnLocquy2 As Boolean = False
    Dim blnLocnam2 As Boolean = False
    Dim blnLocSoxe2 As Boolean = False
    Dim blnLocTaixe2 As Boolean = False
    Dim filterTab2 As Boolean = False
    Dim _isNewOilPayment As Boolean = False
    Dim _isEditOilPayment As Boolean = False
    Dim isLoadcbMonth As Boolean = False
    Dim isLoadcbYear As Boolean = False

    Dim moilPay As New MOilPayments

    Dim TotRowCountOidPayment As Integer
    Dim RowId As Integer
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()
        DataGridViewHelper.DataGridView_InitEvent(gridTotalMonth)
        ' Add any initialization after the InitializeComponent() call.

    End Sub
    Sub ReloadData()
        'gridTotalMonth.DataSource = Nothing
        'Try
        Dim source As New BindingSource
        source.DataSource = moil.getPaymentMonthList(0, 0)
        BindingNavigator1.BindingSource = source
        gridTotalMonth.DataSource = source
        'gridTotalMonth.Columns(0).Visible = False
        gridTotalMonth.AllowUserToAddRows = False
        gridTotalMonth.ReadOnly = True

        If source.Count = 0 Then
            gridOilManager.DataSource = Nothing
            gridOilPayment.DataSource = Nothing
        End If

        'Catch ex As Exception
        '    MessageBox.Show(ex.Message)
        'End Try

        isLoadcbMonth = True
        isLoadcbYear = True
    End Sub
    Sub BindingToGridTotal()
        'Load năm vào combox year
        Dim currentYear As Integer = DateTime.Now().Year
        Dim cbI As New DevComponents.DotNetBar.ComboBoxItem
        'cbI.Text = "------"
        'cbYear.Items.Add(cbI)
        For index = 0 To -5 Step -1
            cbI = New DevComponents.DotNetBar.ComboBoxItem
            cbI.Text = currentYear + index
            cbYear.Items.Add(cbI)
            ' cbYear.Items.Add(currentTime + index)
        Next
        cbYear.Text = currentYear
        'Load tháng vào combobox 
        Dim currentMonth As Integer = DateTime.Now.Month
        cbI = New DevComponents.DotNetBar.ComboBoxItem
        cbI.Text = "------"
        cbMonthSum.Items.Add(cbI)
        For index = 1 To 12 Step 1
            cbI = New DevComponents.DotNetBar.ComboBoxItem
            cbI.Text = index
            cbMonthSum.Items.Add(cbI)
            ' cbYear.Items.Add(currentTime + index)
        Next

        cbMonthSum.Text = currentMonth
        Try
            'gridTotalMonth.DataSource = moilPay.getPaymentMonthList(0, 0)
            ''gridTotalMonth.Columns(0).Visible = False
           
            Dim source As New BindingSource
            source.DataSource = moil.getPaymentMonthList(0, 0)
            BindingNavigator1.BindingSource = source
            gridTotalMonth.DataSource = source
            gridTotalMonth.AllowUserToAddRows = False
            gridTotalMonth.ReadOnly = True
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        isLoadcbMonth = True
        isLoadcbYear = True
    End Sub

    Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
        btnSaveEndMonth.Enabled = True
        'Tính tổng tiền thanh toán
        txtDiscount.Text = ""
        Try
            Dim cbI As DevComponents.DotNetBar.ComboBoxItem = cbYear.SelectedItem
            Dim year As Integer
            If Not cbI.Text.Contains("----") Then
                year = CInt(cbI.Text)
            Else

            End If
            cbI = cbMonthSum.SelectedItem
            Dim month As Integer
            If Not cbI.Text.Contains("----") Then
                month = CInt(cbI.Text)
            Else
                month = 0
            End If

            Dim query1 = moilPay.GetPaymentList2(cbMonthSum.Text, 0, cbYear.Text)
            gridOilPayment.DataSource = query1
            Dim query2 = moil.getOilfeulList4(cbMonthSum.Text, cbYear.Text)
            gridOilManager.DataSource = query2

            Try
                txtPreviousMonth.Text = moilPay.getPreviousAmount(month, year)

            Catch ex As Exception
                txtPreviousMonth.Text = 0

            End Try
            Try
                txtSumPayment.Text = moilPay.getSumofMoneyPayment(month, year)

            Catch ex As Exception
                txtSumPayment.Text = 0
            End Try
            Try
                'Tổng số lít dầu
                txtSumLiter.Text = moil.getSumofLiter(month, year)
            Catch ex As Exception
                txtSumLiter.Text = 0
            End Try
            Try
                'Tổng tiền đổ dầu
                txtSumPushOil.Text = moil.getSumofMoney(month, year)
            Catch ex As Exception
                txtSumPushOil.Text = 0
            End Try

            ' TÍnh số tiền còn thừa
            Dim sumpayment As Integer
            Dim previousMonth As Integer
            Dim discount As Integer
            Dim sumpushoial As Integer
            If txtSumPayment.Text <> "" Then
                sumpayment = CInt(txtSumPayment.Text.Replace(",", ""))
            Else
                sumpayment = 0
            End If

            If txtPreviousMonth.Text <> "" Then
                previousMonth = CInt(txtPreviousMonth.Text.Replace(",", ""))
            Else
                previousMonth = 0
            End If

            If txtDiscount.Text <> "" Then
                discount = CInt(txtDiscount.Text.Replace(",", ""))
            Else
                discount = 0
            End If

            If txtSumPushOil.Text <> "" Then
                sumpushoial = CInt(txtSumPushOil.Text.Replace(",", ""))
            Else
                sumpushoial = 0
            End If

            Dim excessCash = sumpayment + previousMonth + discount - sumpushoial
         
            txtExcessCash.Text = excessCash
            If excessCash < 0 Then
                'tiền âm, không lưu vào mà thông báo
                MessageBox.Show("Số tiền nợ là: " + txtExcessCash.Text)
                txtExcessCash.Text = "0"
                Return
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        txtDiscount.Focus()
    End Sub
    'Tự động tính toán ngày hiện tại load ucControl
    Sub AutoCalculate()
        'Tính tổng tiền thanh toán
        Try

            Dim year As Integer = DateTime.Now.Year
        

            Dim month As Integer = DateTime.Now.Month
          
            Try
                txtPreviousMonth.Text = moilPay.getPreviousAmount(month, year)

            Catch ex As Exception
                txtPreviousMonth.Text = 0

            End Try
            Try
                txtSumPayment.Text = moilPay.getSumofMoneyPayment(month, year)

            Catch ex As Exception
                txtSumPayment.Text = 0
            End Try
            Try
                'Tổng số lít dầu
                txtSumLiter.Text = moil.getSumofLiter(month, year)
            Catch ex As Exception
                txtSumLiter.Text = 0
            End Try
            Try
                'Tổng tiền đổ dầu
                txtSumPushOil.Text = moil.getSumofMoney(month, year)
            Catch ex As Exception
                txtSumPushOil.Text = 0
            End Try

            ' TÍnh số tiền còn thừa
            Dim sumpayment As Integer
            Dim previousMonth As Integer
            Dim discount As Integer
            Dim sumpushoial As Integer
            If txtSumPayment.Text <> "" Then
                sumpayment = CInt(txtSumPayment.Text.Replace(",", ""))
            Else
                sumpayment = 0
            End If

            If txtPreviousMonth.Text <> "" Then
                previousMonth = CInt(txtPreviousMonth.Text.Replace(",", ""))
            Else
                previousMonth = 0
            End If

            If txtDiscount.Text <> "" Then
                discount = CInt(txtDiscount.Text.Replace(",", ""))
            Else
                discount = 0
            End If

            If txtSumPushOil.Text <> "" Then
                sumpushoial = CInt(txtSumPushOil.Text.Replace(",", ""))
            Else
                sumpushoial = 0
            End If

            Dim excessCash = sumpayment + previousMonth + discount - sumpushoial
            txtExcessCash.Text = excessCash
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        ''Tự động lưu thông tin và load lại 


        Dim obj As New tblTotalMonth
        Dim isExist As Integer = moilPay.IsExistTotalMonth(obj.Month, obj.Year)


        If txtSumLiter.Text <> "" Then
            obj.TotalLiter = CInt(txtSumLiter.Text.Replace(",", ""))
        End If

        If txtSumPayment.Text <> "" Then
            obj.TotalPayment = CInt(txtSumPayment.Text.Replace(",", ""))

        End If


        If txtPreviousMonth.Text <> "" Then
            obj.PreviousMonth = CInt(txtPreviousMonth.Text.Replace(",", ""))
        End If

        If txtDiscount.Text <> "" Then
            obj.Discount = CInt(txtDiscount.Text.Replace(",", ""))

        End If

        If txtSumPushOil.Text <> "" Then
            obj.TotalMoneyPush = CInt(txtSumPushOil.Text.Replace(",", ""))

        End If

        If txtExcessCash.Text <> "" Then
            obj.ExcessMonth = CInt(txtExcessCash.Text.Replace(",", ""))

        End If

        If isExist = 0 Then
            'Chưa lưu thì thêm mới
            moil.InsertTotalMonth(obj)
        Else
            obj.ID = CInt(txtIDTotalMonth.Text)
            moil.UpdateTotalMonth(obj)
        End If
        ReloadData()
    End Sub
    Private Sub txtSumPayment_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSumPayment.TextChanged
 
        util.FormatCurr(txtSumPayment)
    End Sub

    Private Sub txtSumPushOil_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSumPushOil.TextChanged
        'Dim str As String = txtSumPushOil.Text
        'Dim start As Integer = txtSumPushOil.Text.Length - txtSumPushOil.SelectionStart
        'str = str.Replace(",", "")
        'txtSumPushOil.Text = FormatMoney(str)
        'txtSumPushOil.SelectionStart = -start + txtSumPushOil.Text.Length
        util.FormatCurr(txtSumPushOil)
    End Sub

    Private Sub txtPreviousMonth_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPreviousMonth.TextChanged
        'Dim str As String = txtPreviousMonth.Text
        'Dim start As Integer = txtPreviousMonth.Text.Length - txtPreviousMonth.SelectionStart
        'str = str.Replace(",", "")
        'txtPreviousMonth.Text = FormatMoney(str)
        'txtPreviousMonth.SelectionStart = -start + txtPreviousMonth.Text.Length
        util.FormatCurr(txtPreviousMonth)
    End Sub

    Private Sub txtDiscount_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtDiscount.TextChanged
        'Dim str As String = txtDiscount.Text
        'Dim start As Integer = txtDiscount.Text.Length - txtDiscount.SelectionStart
        'str = str.Replace(",", "")
        'txtDiscount.Text = FormatMoney(str)
        'txtDiscount.SelectionStart = -start + txtDiscount.Text.Length
        util.FormatCurr(txtDiscount)
    End Sub

    Private Sub btnSaveEndMonth_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveEndMonth.Click
        'Lưu số tiền đã tính được của tháng
        'Kiểm tra xem ngày tháng này đã lưu hay chưa


        Dim obj As New tblTotalMonth

        If cbMonthSum.Text.Contains("-----") Then
            MessageBox.Show("Phải chọn tháng để lưu")
            Return
        Else
            obj.Month = CInt(cbMonthSum.Text)

        End If
        If cbYear.Text.Contains("-----") Then
            MessageBox.Show("Phải chọn năm để lưu")
            Return

        Else
            obj.Year = CInt(cbYear.Text)

        End If

        Dim isExist As Integer = moilPay.IsExistTotalMonth(obj.Month, obj.Year)


        If txtSumLiter.Text <> "" Then
            obj.TotalLiter = CInt(txtSumLiter.Text.Replace(",", ""))
        End If

        If txtSumPayment.Text <> "" Then
            obj.TotalPayment = CInt(txtSumPayment.Text.Replace(",", ""))

        End If


        If txtPreviousMonth.Text <> "" Then
            obj.PreviousMonth = CInt(txtPreviousMonth.Text.Replace(",", ""))
        End If

        If txtDiscount.Text <> "" Then
            obj.Discount = CInt(txtDiscount.Text.Replace(",", ""))

        End If

        If txtSumPushOil.Text <> "" Then
            obj.TotalMoneyPush = CInt(txtSumPushOil.Text.Replace(",", ""))

        End If

        If txtExcessCash.Text <> "" Then
            obj.ExcessMonth = CInt(txtExcessCash.Text.Replace(",", ""))

        End If

        If isExist = 0 Then
            'Chưa lưu thì thêm mới
            moil.InsertTotalMonth(obj)
            ReloadData()
        Else
            'obj.ID = CInt(txtIDTotalMonth.Text)
            obj.Month = cbMonthSum.Text
            obj.Year = cbYear.Text

            moil.UpdateTotalMonth(obj)
            ReloadData()
        End If

        btnSaveEndMonth.Enabled = False
        'BindingToGridTotal()
    End Sub

    Private Sub FormatGrid()
        gridTotalMonth.Columns(0).Visible = False
        gridTotalMonth.Columns(3).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        gridTotalMonth.Columns(3).DefaultCellStyle.Format = "#,##0.##"
        gridTotalMonth.Columns(4).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        gridTotalMonth.Columns(4).DefaultCellStyle.Format = "#,##0.##"
        gridTotalMonth.Columns(5).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        gridTotalMonth.Columns(5).DefaultCellStyle.Format = "#,##0.##"
        gridTotalMonth.Columns(6).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        gridTotalMonth.Columns(6).DefaultCellStyle.Format = "#,##0.##"
        gridTotalMonth.Columns(7).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        gridTotalMonth.Columns(7).DefaultCellStyle.Format = "#,##0.##"
        gridTotalMonth.Columns(8).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        gridTotalMonth.Columns(8).DefaultCellStyle.Format = "#,##0.##"
    End Sub
     

    Private Sub cbMonthSum_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbMonthSum.SelectedIndexChanged
        'Khi thay đổi tháng cũng load lại dữ liệu
        'Try
        '    If isLoadcbMonth Then
        '        'Nếu đã load được dữ liệu tháng
        '        Dim query = Nothing
        '        If cbMonthSum.Text.Contains("----") Then
        '            'Nếu vậy thì load toàn bộ dữ liệu
        '            query = moilPay.getPaymentMonthList(0, cbYear.Text)

        '        Else
        '            query = moilPay.getPaymentMonthList(cbMonthSum.Text, cbYear.Text)


        '        End If
        '        gridTotalMonth.DataSource = query
        '    End If
        'Catch ex As Exception

        'End Try


    End Sub

    Private Sub cbYear_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbYear.SelectedIndexChanged
        ''Khi thay đổi tháng cũng load lại dữ liệu

        'If isLoadcbYear Then
        '    'Nếu đã load được dữ liệu tháng

        '    If cbMonthSum.Text.Contains("----") Then
        '        'Nếu vậy thì load toàn bộ dữ liệu
        '        gridTotalMonth.DataSource = moilPay.getPaymentMonthList(0, cbYear.Text)
        '        'gridTotalMonth.Columns(0).Visible = False
        '        gridTotalMonth.Columns(1).Visible = False
        '    Else
        '        gridTotalMonth.DataSource = moilPay.getPaymentMonthList(cbMonthSum.Text, cbYear.Text)
        '        'gridTotalMonth.Columns(0).Visible = False

        '    End If

        'End If
    End Sub

    Private Sub LoadImport()
        'util.FillDriverCombo(cbgridSign)
        'util.FillTruckCombo(cbTruck)
        'util.FillDriverCombo(cbDriverName)
        Bar1.Name = "Details"
    End Sub
    Private Sub ucTongXangDau_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        LoadImport()
        Bar1.CanHide = True
        BindingToGridTotal()
        'AutoCalculate()
        isNewOilExpense = False
    End Sub

    Private Sub txtSumLiter_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSumLiter.TextChanged

    End Sub

    Private Sub txtExcessCash_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtExcessCash.TextChanged
        util.FormatCurr(txtExcessCash)
    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim uti As New Utilities
        Try
            Dim result As Integer
            result = uti.ShowConfirm("Xác nhận", "Bạn chắc chắn muốn xoá phiếu chi này?")
            If result = DialogResult.Yes Then
                'Đồng ý xóa
                moil.DeleteRecordTotalMonth(txtIDTotalMonth.Text)
                ReloadData()
            End If
        Catch ex As Exception

        End Try
    End Sub
 

    
    Private Sub gridTotalMonth_RowEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridTotalMonth.RowEnter
        Try

            Dim rw As Integer = e.RowIndex
            Dim dg As DataGridView = CType(sender, DataGridView)
            'Tổng tiền chi trả đổ dầu trong tháng
            txtSumPayment.Text = dg.Item(3, rw).Value   'row.Item("id").ToString
            'Tiền tháng trước
            txtPreviousMonth.Text = dg.Item(4, rw).Value 'row.Item("menu_desc").ToString
            'Tiền chiết khấu
            txtDiscount.Text = dg.Item(5, rw).Value 'row.Item("caption").ToString
            'Tổng số lít dầu
            txtSumLiter.Text = dg.Item(6, rw).Value
            'Tổng tiền đổ dầu
            txtSumPushOil.Text = dg.Item(7, rw).Value
            'Tiền thừa
            txtExcessCash.Text = dg.Item(8, rw).Value
            txtIDTotalMonth.Text = dg.Item(0, rw).Value
            cbMonthSum.Text = dg.Item(1, rw).Value
            cbYear.Text = dg.Item(2, rw).Value

            'If dg.Item(1, rw).Value IsNot Nothing Then

            '    cbMonthSum.Text = dg.Item(1, rw).Value
            'End If
            'If dg.Item(2, rw).Value IsNot Nothing Then

            '    cbYear.Text = dg.Item(2, rw).Value
            'End If
            'Load thông tin cụ thể

            Dim query1 = moilPay.GetPaymentList2(dg.Item(1, rw).Value, 0, dg.Item(2, rw).Value)
            gridOilPayment.DataSource = query1
            Dim query2 = moil.getOilfeulList4(dg.Item(1, rw).Value, dg.Item(2, rw).Value)
            gridOilManager.DataSource = query2
        Catch ex As Exception

        End Try
    End Sub

    Private Sub gridTotalMonth_DataBindingComplete(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles gridTotalMonth.DataBindingComplete
        FormatGrid()
    End Sub
End Class
 